package com.chen.demo.wechat.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.chen.demo.wechat.domain.User;
import com.chen.demo.wechat.service.UserService;
import com.chen.demo.wechat.util.SignUtil;

@RestController
public class UserController {
	@Autowired 
	private UserService userService;
	
	@RequestMapping("/findAll")
	public List<User> findAll(){
		System.out.println(userService.findAll());
		return userService.findAll();
	}
	@RequestMapping("/getById/{id}")
	public User getById(@PathVariable int id){
		System.out.println(id);
		return userService.findById(id);
	}
//	@RequestMapping("/wx")
	public String helloworld(@RequestParam String signature
							,@RequestParam String timestamp
							,@RequestParam String nonce
							,@RequestParam String echostr){
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			System.out.println(echostr);
			return echostr;
		}
		return null;
	}
	@RequestMapping("/wx")
	public String helloworld(HttpServletRequest request,HttpServletResponse response) throws IOException{
		request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");  
  
        /** 读取接收到的xml消息 */  
        StringBuffer sb = new StringBuffer();  
        InputStream is = request.getInputStream();  
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");  
        BufferedReader br = new BufferedReader(isr);  
        String s = "";  
        while ((s = br.readLine()) != null) {  
            sb.append(s);  
        }  
        String xml = sb.toString(); //次即为接收到微信端发送过来的xml数据  
  
        String result = ""; 
        /** 判断是否是微信接入激活验证，只有首次接入验证时才会收到echostr参数，此时需要把它直接返回 */  
        String echostr = request.getParameter("echostr");  
        if (echostr != null && echostr.length() > 1) {  
            result = echostr;  
        } else {  
            //正常的微信处理流程  
            result = new WechatProcess().processWechatMag(xml);  
        }  
        return result;
	}
	
	@RequestMapping("/")
	public ModelAndView getString(Model model){
		ModelAndView mav = new ModelAndView("redirect:index.html");
		mav.addObject("name", "chenbinghui");
		return mav;
	}
}
